package com.ruoyi.web.controller.system;

import com.alibaba.fastjson.JSON;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.bean.dto.WeightUserLoginDto;
import com.ruoyi.system.domain.WeightUserConfig;
import com.ruoyi.system.service.WeightUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * 时间用户管理
 */
@Slf4j
@RestController
@RequestMapping("/weight/weightUser")
public class WeightUserController {

    @Autowired
    private WeightUserService weightUserService;

    @Log(title = "时间用户注册", businessType = BusinessType.INSERT)
    @PostMapping("/register")
    @ResponseBody
    public AjaxResult registerWeightUser(@Validated WeightUserConfig config) {
        String userName = config.getUserName();
        if (StringUtils.isEmpty(userName)) {
            return AjaxResult.error("用户姓名为空");
        }

        int i1 = weightUserService.selectWeightUserByName(config);
        if (i1 > 0) {
            return AjaxResult.error("存在相同用户，请修改用户名");
        }

        String userPassword = config.getUserPassword();
        if (StringUtils.isEmpty(userPassword)) {
            return AjaxResult.error("用户密码为空");
        }

        int i = weightUserService.inserWeightUser(config);
        if (i == 1) {
            return AjaxResult.success("新增成功");
        } else {
            return AjaxResult.error("新增失败");
        }
    }

    @Log(title = "时间用户登录", businessType = BusinessType.INSERT)
    @PostMapping("/login")
    @ResponseBody
    public AjaxResult login(@RequestBody @Validated WeightUserLoginDto config) {

        log.info("登录开始:{}", JSON.toJSONString(config));

        String userName = config.getUserName();
        if (StringUtils.isEmpty(userName)) {
            return AjaxResult.error("用户姓名为空");
        }

        String userPassword = config.getUserPassword();
        if (StringUtils.isEmpty(userPassword)) {
            return AjaxResult.error("用户密码为空");
        }

        Integer i = weightUserService.selectWeightUserByNamePassword(config);
        if (i != null) {
            return AjaxResult.success("登录成功", i);
        } else {
            return AjaxResult.error("登录失败");
        }
    }

}
